/**
 * 
 */
package com.ideazd.api.controller;


import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ideazd.api.model.Topic;
import com.ideazd.api.model.TopicComment;
import com.ideazd.api.model.TopicPraise;
import com.ideazd.api.model.dto.RetDTO;
import com.ideazd.api.service.TopicService;
import com.ideazd.api.tools.DateUtil;
import com.ideazd.api.tools.SysUtil;
import com.ideazd.api.util.KeyWordReplace;
import com.jfinal.core.Controller;
import com.jfinal.ext.route.ControllerBind;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Logger;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;

/**
 * @author yzz
 * @create 2016年3月21日 下午3:08:17
 */
@ControllerBind(controllerKey="topic")
public class TopicController extends Controller {
	private static final Logger log = Logger.getLogger(TopicController.class);
	private TopicService topicService = new TopicService();
	
	/**
	 * 话题列表
	 */
	public void getTopicList(){
		String pageIndex = getPara("pageIndex");
		String useId = getPara("useId");
		Map<Object, Object> ret = new HashMap<Object,Object>();
		
		
		if(StrKit.isBlank(pageIndex)){
			ret.put("code","-2");
			ret.put("msg","必传参数不允许为空");
			renderJson(ret);
			return;
		}
		
		String sql = "";
		
		if(!StrKit.isBlank(useId)){
			sql = "and useid = '"+useId+"'";
		}
		
		
		
		try {
			
			Page<Topic> topicPage = topicService.getTopicPage(pageIndex,sql,"createdate");
			List<Map<Object, Object>> topicList = new ArrayList<Map<Object, Object>>();
			
			for(Topic top : topicPage.getList()){
				boolean isClick = false;
				Map<Object, Object> topic = new HashMap<Object,Object>();
				topic.put("topId", top.get("topid"));
				topic.put("topTitle", KeyWordReplace.replaceKeyWord(URLDecoder.decode(top.getStr("toptitle"))));
				
				if(!StrKit.isBlank(useId)){
					TopicPraise topicPraise = TopicPraise.dao.findFirst("select * from sta_topic_praise where useid = '"+useId+"' and topid = '"+top.get("topid")+"'");
					if(null != topicPraise){
						isClick = true;
					}
				}
				
				if(StrKit.isBlank(SysUtil.validateStr(top.get("toppicture")))){
					topic.put("topPicture","");
				}else{
					topic.put("topPicture", PropKit.get("server_uri") + top.get("toppicture"));
				}
				
				topic.put("isClick", isClick);
				topic.put("readAmount", top.get("readamount"));
				topic.put("clickAmount", top.get("clickamount"));
				topic.put("commentAmount", top.get("commentamount"));
				topic.put("createTime", SysUtil.getPublishDate(top.get("createdate").toString()));
				topicList.add(topic);
				
				
			}
			
			if(!StrKit.isBlank(useId)){
				Db.update("update sta_topic set unread = '0' where createid = '"+useId+"'");
			}
			
			Map<Object, Object> data = new HashMap<Object,Object>();
			data.put("totalPage", topicPage.getTotalPage());
			data.put("topicList", topicList);
			
			ret.put("code","0");
			ret.put("msg","成功");
			ret.put("data", data);
			
		} catch (Exception e) {
			ret.put("code","-1");
			ret.put("msg",e.getMessage());
		}
		
		renderJson(ret);
		return;
		
	}
	
	/**
	 * 话题详情
	 */
	public void getTopicDetail(){
		String topId  = getPara("topId");
		String useId = getPara("useId");
		RetDTO ret = new RetDTO();
		
		if(StrKit.isBlank(topId)){
			ret.setCode("-2");
			ret.setMsg("必传参数不允许为空");
			renderJson(ret);
			return;
		}
		
		try {
			
			boolean isClick = false;
			
			
			
			Topic topic = Topic.dao.findFirst("select t.*,u.headportrait,u.nickname,u.gender from sta_topic t left join sta_user u on u.useid = t.useid where topid = '"+topId+"' ");
			ret.put("topId", topic.get("topid"));
			ret.put("topTitle",KeyWordReplace.replaceKeyWord(URLDecoder.decode(topic.getStr("toptitle"))));
			
			if(!StrKit.isBlank(useId)){
				TopicPraise topicPraise = TopicPraise.dao.findFirst("select * from sta_topic_praise where useid = '"+useId+"' and topid = '"+topic.get("topid")+"'");
				if(null != topicPraise){
					isClick = true;
				}
			}
			
			if(StrKit.isBlank(SysUtil.validateStr(topic.get("toppicture")))){
				ret.put("topPicture","");
			}else{
				ret.put("topPicture", PropKit.get("server_uri") + topic.get("toppicture"));
			}
			ret.put("isClick", isClick);
			ret.put("topContent", KeyWordReplace.replaceKeyWord(URLDecoder.decode(topic.getStr("topcontent"))));
			ret.put("readAmount", topic.get("readamount"));
			ret.put("clickAmount", topic.get("clickamount"));
			ret.put("shareUrl", topic.get("topid"));
			ret.put("nickName", topic.get("nickname"));
			ret.put("gender", topic.get("gender"));
			ret.put("headPortrait", topic.get("headportrait"));
			ret.put("createTime", SysUtil.getPublishDate(topic.get("createtime").toString()));
			
			if(topic.get("createid").equals(useId)){
				Topic upTopic = new Topic();
				upTopic.set("topid", topic.get("topid"));
				upTopic.set("unread", "0");
				
				upTopic.update();
			}
			
			
			ret.setCode("0");
			ret.setMsg("成功");
			
		} catch (Exception e) {
			ret.setCode("-1");
			ret.setMsg(e.getMessage());
		}
		
		renderJson(ret);
		return;
	}
	
	/**
	 * 获取话题评论列表
	 */
	public void getTopicCommentList(){
		String curPageStr = getPara("pageIndex");
		String topicId = getPara("topId");
		int pageSize = 10;
		int curPage = 1;
		
		Map<Object,Object> ret = new HashMap<Object,Object>();
		
		if(!StrKit.isBlank(curPageStr)){
        	curPage = Integer.parseInt(curPageStr);
        }

		String sql = "from sta_topic_comment c left join sta_user u on c.useid = u.useid left join sta_user cu on cu.useid = c.commentuseid  where c.topid = '"+topicId+"' and c.delflag = '0'";
		
		try {
			Map<Object,Object> data = new HashMap<Object,Object>();
			Page<TopicComment> topicCommentPage = TopicComment.dao.paginate(curPage, pageSize, "select c.*,u.nickname,cu.nickname as 'commentnickname'", sql+" order by c.createtime desc");
	        List<Map<String, String>> topicCommentList = new ArrayList<Map<String, String>>();
	        
	        for(TopicComment t:topicCommentPage.getList()){
	        	Map<String, String> topicComment = new HashMap<String, String>();
	        	topicComment.put("comId", t.getStr("comid"));
	        	topicComment.put("topId", t.getStr("topid"));
	        	topicComment.put("comContent",  KeyWordReplace.replaceKeyWord(URLDecoder.decode(t.getStr("comcontent"))));
	        	topicComment.put("nickName", SysUtil.validateStr(t.get("nickname")));
	        	topicComment.put("useId", t.getStr("useid"));
	        	topicComment.put("createTime", t.get("createtime").toString());
	        	
	        	if(null != t.get("commentuseid")){

		        	topicComment.put("comNickName", SysUtil.validateStr(t.get("commentnickname")));
		        	topicComment.put("comUseId", t.getStr("commentuseid"));
	        	}else{

		        	topicComment.put("comNickName", "");
		        	topicComment.put("comUseId", "");
	        	}
	        	
	        	topicCommentList.add(topicComment);
	        }
	        data.put("commentList", topicCommentList);
	        data.put("totalPage", topicCommentPage.getTotalPage());
	        
	        
	        ret.put("data", data);
	        ret.put("code", "0");
	        ret.put("msg", "成功");
			
		}catch (Exception e) {
			ret.put("code", "-1");
	        ret.put("msg", "系统异常");
		}
		
		renderJson(ret);
		return;
	}
	
	/**
	 * 发布话题
	 */
	public void publishTopic(){
		String useId = getPara("useId");
		String topTitle = getPara("topTitle");
		String topContent = getPara("topContent");
		String topPicture = getPara("topPicture");
		RetDTO ret = new RetDTO();
		
		if(StrKit.isBlank(useId)||StrKit.isBlank(topContent)||StrKit.isBlank(topTitle)){
			ret.setCode("-2");
			ret.setMsg("必传参数不允许为空");
			renderJson(ret);
			return;
		}

		try {

			String uuid = SysUtil.getUUID();

			// 图片上传
			if (!StrKit.isBlank(topPicture)) {

				Map<String, String> imaPath = SysUtil.uploadImg(getRequest(),
						topPicture,
						"/upload/topicpost" + "/" + uuid + "/images" + "/"
								+ DateUtil.formatDate(new Date(), "yyyyMMdd")
								+ "/");

				topPicture = imaPath.get("serverPath");

			}

			Topic topicPost = new Topic();
			topicPost.set("topid", uuid);
			topicPost.set("useid", useId);
			topicPost.set("toptitle", topTitle);
			topicPost.set("toppicture", topPicture);
			topicPost.set("topcontent", topContent);
			topicPost.set("createtime", new Date());
			topicPost.set("displayorder", "0");
			topicPost.set("displaystatus", "0");
			topicPost.set("readamount", "0");
			topicPost.set("commentamount", "0");
			topicPost.set("clickamount", "0");
			topicPost.set("unread", "0");
			topicPost.set("createid", useId);
			topicPost.set("createname", "接口用户创建");
			topicPost.set("createdate", new Date());
			topicPost.set("updateid", useId);
			topicPost.set("updatename", "接口用户创建");
			topicPost.set("updatedate", new Date());
			topicPost.set("remarks", "接口用户创建");
			topicPost.save();

			ret.setCode("0");
			ret.setMsg("成功");

		} catch (Exception e) {
			ret.setCode("-1");
			ret.setMsg(e.getMessage());
		}

		renderJson(ret);
		return;
	}
	
	/**
	 * 点赞取消点赞
	 */
	public void isClickLike(){
		String topId = getPara("topId");
		String useId = getPara("useId");
		
		RetDTO ret = new RetDTO();
		
		try{
			
			TopicPraise praise = TopicPraise.dao.findFirst("select * from sta_topic_praise where topid = '"+topId+"' and useId = '"+useId+"'");
			
			if(null == praise){
				praise = new TopicPraise();
				praise.set("praid", SysUtil.getUUID());
				praise.set("topid", topId);
				praise.set("useid",useId );
				praise.set("createtime", new Date());
				
				if(praise.save()){
					Db.update("update sta_topic set clickamount=clickamount+1 where topid = '"+topId+"'");
				}
			}else{
				TopicPraise.dao.deleteById(praise.get("praid"));
				Db.update("update sta_topic set clickamount=clickamount-1 where topid = '"+topId+"'");
			}
			
			
			
			ret.setCode("0");
			ret.setMsg("成功");
		}catch(Exception e){
			ret.setCode("10003");
			ret.setMsg(e.getMessage());
		}
		renderJson(ret);
		return;
	}
	
}
